package com.cosytek.farmmanager;


import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import org.json.JSONObject;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MsgFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MsgFragment extends Fragment implements MsgManager.NotifyListener {
    private String mToken;

    private ListView mListView;
    private MsgFragmentAdapter mListAdapter;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     * @return A new instance of fragment MsgFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MsgFragment newInstance() {
        MsgFragment fragment = new MsgFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    public MsgFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_msg, container, false);
        mListView = (ListView)view.findViewById(R.id.frag_msg_msg_list);
        mListAdapter = new MsgFragmentAdapter(inflater);
        mListView.setAdapter(mListAdapter);
        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        MsgManager.instance().addListener(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        MsgManager.instance().removeListener(this);
    }

    @Override
    public void onJSONNotify(int msdId, String type, JSONObject jsonObject) {
        mListAdapter.invalidate();
        mListView.smoothScrollToPosition(0);
    }
}
